package services;

import dao.CommentDAO;
import dao.UserDAO;
import model.Comment;
import model.Page;
import model.Reply;
import model.User;
import net.sf.json.JSONArray;
import utils.C3P0Util;
import utils.MyJSONUtils;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

/**
 * 提供评论的相关服务
 */
public class CommentServices {

    private CommentDAO commentDAO;
    private UserDAO userDAO;

    public CommentServices() {
        commentDAO = new CommentDAO();
        userDAO = new UserDAO();
    }

    /**
     * 获得某一页所有评论，包括发布人，回复
     *
     * @param comicId 漫画id
     * @return 评论的jsonarray
     */
    public JSONArray getComicComments(int comicId, Page page) {

        //先获得这一页的所有评论
        List<Comment> lists_comment = commentDAO.getComicComments(comicId, page);

        ReplyServices res = new ReplyServices();

        //使用公用的coon完成多次查询
        Connection coon = C3P0Util.getConnection();

        //遍历每一个评论进行操作
        for (Comment comment : lists_comment) {
            User user = userDAO.getUserByName(comment.getUser_name());
            comment.setUser(user);//评论添加发布人信息

            Page replyPage = res.getReplyPage(comment.getId(), coon);//获得回复分页
            comment.setReplyPage(replyPage);

            List<Reply> replyList = res.getPageReplys(comment.getId(), replyPage, coon);//获得所有回复
            comment.setReplys(replyList);

        }

        //使用自定义的coon需要手动关闭连接
        try {
            if (coon != null) {
                coon.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return JSONArray.fromObject(lists_comment, MyJSONUtils.jsonConfig);
    }

    /**
     * 添加评论
     *
     * @param user_name 用户名
     * @param comic_id  漫画id
     * @param content   内容
     * @return true如果成功更新
     */
    public boolean addComment(String user_name, String comic_id, String content) {
        return commentDAO.addComment(user_name, Integer.parseInt(comic_id), content);
    }

    /**
     * 获得该漫画的评论总数
     *
     * @param comicId 漫画id
     * @return 数量
     */
    public int getCommentCounts(String comicId) {
        return commentDAO.getCommentCounts(Integer.parseInt(comicId));
    }

    /**
     * 获得评论占多少页面
     *
     * @param comicId 漫画id
     * @return 页数
     */
    public Page getCommentPage(String comicId) {
        Page page1 = new Page(1);
        int count = getCommentCounts(comicId);
        page1.setTotal(count);
        return page1;
    }

    public int getPageSize() {
        return new Page().getPageSize();
    }
}
